#!/usr/bin/env python

from scapy.all import *
from time import sleep
from threading import Thread
import IPy
from scapy.layers.dhcp import BOOTP, DHCP
from scapy.layers.l2 import Ether
import _thread

flag = 0
dhcp_address = '0.0.0.0'
current_subnet = '0.0.0.0'


def sendDHCPDescover():
    global flag
    print("[+] Geting The DHCP server IP Address!")
    for i in range(0,4):
        print("getdhcpip running")
        #tap_interface = 'a0:a4:c5:1e:f4:1a'
        tap_interface = 'WLAN'
        src_mac_address = RandMAC()
        ethernet = Ether(dst='ff:ff:ff:ff:ff:ff',
                         src=src_mac_address,
                         type=0x800)
        ip = IP(src='0.0.0.0', dst='255.255.255.255')
        udp = UDP(sport=68, dport=67)
        fam, hw = get_if_raw_hwaddr(tap_interface)
        bootp = BOOTP(chaddr=hw, ciaddr='0.0.0.0', xid=0x01020304, flags=1)
        dhcp = DHCP(options=[("message-type", "discover"),
                             ("vendor_class_id", "DIXIN.DEV.TEST"),
                             "end"])
        packet = ethernet / ip / udp / bootp / dhcp
        sendp(packet, count=1, verbose=0)
        sleep(0.1)

def dhcpClientStart(param):
    print("dhcpClientStart start...")
    sniff(filter='port 67 or port 68', prn=procesar_Peticiones_Dhcp)

def procesar_Peticiones_Dhcp(paquete):
    if paquete[DHCP]:
        print('Got a DHCP message')
        print("l------1", paquete[DHCP])
        for i in range(0, len(paquete[DHCP].options)):
            print("==========The options[%d]=" % (i), paquete[DHCP].options[i])
        print("============================end=======================")
        if paquete[DHCP].options[0][1] == 2:
            print("l------2", paquete[BOOTP].yiaddr)
            print("l------3", str(paquete[BOOTP].sname, 'utf-8'))
            for i in range(0, len(paquete[DHCP].options)):
                if paquete[DHCP].options[i][0] == "vendor_specific":
                    if "DIXIN.SERVER.DHCP" == str(paquete[DHCP].options[i][1],'utf-8'):
                        print("The vendor_specific(%s) is DIXIN server." % (str(paquete[DHCP].options[i][1])))
                    else:
                        print("The vendor_specific(%s) is not DIXIN server ignore it."%(str(paquete[DHCP].options[i][1])))


        print('The client MAC is:', paquete[Ether].src)
    print('procesado', paquete.summary())

def clientMain():
    t = _thread.start_new_thread(dhcpClientStart, ("",))
    print("===========")
    while 1:
        sendDHCPDescover()
        sleep(10)


if __name__ == '__main__':
    # main()
    clientMain()
    print("[+] Attack Over!")
